package org.six11.olive3.tmp;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * 
 * 
 * @author Gabe Johnson <johnsogg@cmu.edu>
 * 
 */
public class TmpClient {

  public TmpClient() {

  }

  public void go(URL url) throws IOException, InterruptedException {
    // connect to the URL
    HttpURLConnection ht = (HttpURLConnection) url.openConnection();

    // set up relevant HTTP parameters
    ht.setRequestMethod("POST");
    ht.setUseCaches(false);
    ht.setDoOutput(true);
    ht.setDoInput(true);
    ht.setRequestProperty("Connection", "Keep-Alive");

    OutputStreamWriter outWriter = new OutputStreamWriter(ht.getOutputStream());
    outWriter.write("this is retarded");
    outWriter.close();

    // It is critical that you access the input stream. If you don't, it seems the connection
    // is never actually sent to the server.
    BufferedReader in = new BufferedReader(new InputStreamReader(ht.getInputStream()));

    String decodedString;
    while ((decodedString = in.readLine()) != null) {
      System.out.println("Server replies: " + decodedString);
    }
    in.close();
  }

  public static void main(String[] args) throws IOException, InterruptedException {
    TmpClient t = new TmpClient();
    int n = 1;
    if (args.length > 0) {
      n = Integer.parseInt(args[0]);
    }
    System.out.println("Running " + n + " time(s)...");
    // form a URL
    URL url = new URL("http://six11.org/olive3/ink");
    System.out.println("Hitting URL: " + url.toExternalForm());
    long start = System.currentTimeMillis();
    for (int i = 0; i < n; i++) {
      t.go(url);
    }
    long now = System.currentTimeMillis();
    long duration = now - start;
    System.out.println("\n* Took " + duration + " milliseconds to go " + n + " time(s).");
  }
}
